<template >
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 提示 信息 -->
      <el-alert class="alertTip" title="注意：只允许为第三级分类设置相关参数！" :closable="false" show-icon type="warning" effect="dark">
      </el-alert>

      <!-- 选择商品分类  -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader style="width:300px" v-model="selectedKeys" :options="parentCateList" :props="cascaderOptions" @change="parentCateChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏区域 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数的的按钮 -->
          <el-button :disabled="isBtnDisable" size="mini" type="primary" @click="addParamsDialog=true">添加参数</el-button>
          <!-- 表格区域 -->
          <el-table stripe :data="manyParamsList" border style="width: 100%">
            <el-table-column type="expand">
              <!-- 展开项属性参数列表 -->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag closable :key="index" v-for="(item,index) in scope.row.attr_vals" @close="handleClose(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsDialog(scope.row.attr_id)">修改</el-button>
                <!-- 删除按钮 -->
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性的的按钮 -->
          <el-button :disabled="isBtnDisable" size="mini" type="primary" @click="addParamsDialog=true">添加属性</el-button>

          <!-- 表格区域 -->
          <el-table stripe :data="onlyParamsList" border style="width: 100%">
            <el-table-column type="expand">
              <!-- 展开项属性参数列表 -->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag closable :key="index" v-for="(item,index) in scope.row.attr_vals" @close="handleClose(index,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 动态可添加的标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsDialog(scope.row.attr_id)">修改</el-button>
                <!-- 删除按钮 -->
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数或者属性的对话框 -->
    <el-dialog :title=" '添加'+ titleText" :visible.sync="addParamsDialog" width="50%" @close="addParamsDialogClosed">
      <el-form :model="addParamsInfo" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input clearable v-model="addParamsInfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加参数或者属性的对话框 -->
    <el-dialog :title=" '修改'+ titleText" :visible.sync="editParamsDialog" width="50%" @close="editParamsDialogClosed">
      <el-form :model="editParamsInfo" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input clearable v-model="editParamsInfo.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择框绑定数据数组
      selectedKeys: [1, 3, 6],
      // 级联选择框数据配置数组
      parentCateList: [],
      // 级联选择框配置对象
      cascaderOptions: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数
      manyParamsList: [],
      // 静态属性
      onlyParamsList: [],
      // tab栏默认显示的页签,通过页签的name属性指定
      activeName: 'many',
      // 添加参数的对话框显示控制值
      addParamsDialog: false,
      // 添加参数的表单数据对象
      addParamsInfo: {
        attr_name: ''
      },
      // 添加参数的表单数据验证规则对象
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '参数不能为空', trigger: 'blur' }
        ]
      },
      // 编辑参数的对话框显示控制值
      editParamsDialog: false,
      // 编辑参数的表单数据对象
      editParamsInfo: {},
      // 编辑参数的表单数据验证规则对象
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '参数不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    // 获取全部的商品分类数据
    async getCateList() {
      const res = await this.$axios.get('categories');
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败！');
      this.parentCateList = res.data;
    },

    // 级联选择框选择数据发生改变的事件函数
    parentCateChange() {
      // console.log(this.selectedKeys);
      // 根据数组的长度来检验用户是否只选择了三级商品分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [1, 3, 6];
        // 防止在级联选择框清楚的时候 表格数据依旧存在
        this.manyParamsList = [];
        this.onlyParamsList = [];
        return this.$message.error('只允许为第三级分类设置参数');
      }
      // console.log(this.selectedKeys);
      this.getParamsList();
    },

    // tab栏点击切换事件函数
    handleTabClick() {
      // console.log(this.activeName);
      this.getParamsList();
    },

    // 根据this.activeName获取 参数列表
    async getParamsList() {
      const res = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } });
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败！');

      // 在这里对attr_vals进行处理，在后台返回的数据是逗号分隔的字符串
      // 把它转换为数组形式
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
        // 给每个item项添加 inputVisible 和 inputValue 属性
        // 这样好在模板里面使用 scope.row.inputValue
        // 动态编辑标签的输入框显示隐藏控制值
        item.inputVisible = false;
        // 动态编辑标签的输入框绑定数据
        item.inputValue = '';
      });

      if (this.activeName === 'many') {
        this.manyParamsList = res.data;
      } else {
        this.onlyParamsList = res.data;
      }
      // console.log(this.manyParamsList);
      // console.log(this.onlyParamsList);
    },

    // 关闭添加参数对话框事件函数，重置表单
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields();
    },

    // 添加参数确定点击事件函数
    addParams() {
      // 提交表单数据预验证
      this.$refs.addParamsFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 验证数据通过，发起请求
        const res = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsInfo.attr_name,
          attr_sel: this.activeName
        });
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error(`添加${this.titleText}失败！`);
        this.$message.success(`添加${this.titleText}成功！`);
        // 刷新用户数据表格
        this.getParamsList();
        // 关闭对话框
        this.addParamsDialog = false;
      });
    },

    // 关闭修改参数对话框事件函数，重置表单
    editParamsDialogClosed() {
      this.$refs.editParamsFormRef.resetFields();
    },

    // 显示修改参数对话框事件函数
    async showEditParamsDialog(attrId) {
      // 根据id获取参数
      const res = await this.$axios.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: {
          attr_sel: this.activeName
        }
      });
      if (res.meta.status !== 200) return this.$message.error(`查询${this.titleText}失败`);

      this.editParamsInfo = res.data;
      // 显示对话框
      this.editParamsDialog = true;
    },

    // 修改参数点击事件函数
    editParams() {
      // 提交表单数据预验证
      this.$refs.editParamsFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 验证数据通过，发起请求
        const res = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsInfo.attr_id}`, {
          attr_name: this.editParamsInfo.attr_name,
          attr_sel: this.activeName
        });
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error(`修改${this.titleText}失败！`);
        this.$message.success(`修改${this.titleText}成功！`);
        // 刷新用户数据表格
        this.getParamsList();
        // 关闭对话框
        this.editParamsDialog = false;
      });
    },

    // 删除参数点击事件
    async deleteParams(attrId) {
      // 弹出信息提示框并通过async/await 简化异步事件操作
      const confirmResult = await this.$confirm(`此操作将永久删除该${this.titleText}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      // console.log(confirmResult);
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除操作！');
      const res = await this.$axios.delete(`categories/${this.cateId}/attributes/${attrId}`);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(`删除${this.titleText}失败！`);
      this.$message.success(`删除${this.titleText}成功！`);

      // 刷新数据列表
      this.getParamsList();
    },

    // 点击加新标签显示输入框
    showInput(row) {
      row.inputVisible = true;
      // Vue 在更新 DOM 时是异步执行的，为了在数据变化之后等待 Vue 完成更新 DOM，可以在数据变化之后立即使用 Vue.nextTick(callback)。这样回调函数将在 DOM 更新完成后被调用。
      // 出现文本框，需要自动获取焦点
      // this.$nextTick(() => this.$refs.saveTagInputRef.$refs.input.focus());
      this.$nextTick(() => this.$refs.saveTagInputRef.focus());
    },

    // 关闭输入框 显示标签
    handleInputConfirm(row) {
      // 如果新标签是空格，就不新加
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = '';
        return;
      }
      // 把新加的页签值保存到attr_vals数组在中
      row.attr_vals.push(row.inputValue.trim());
      row.inputVisible = false;
      row.inputValue = '';
      // 调用 请求函数
      this.saveAttrVals(row, '增加');
    },

    // 根据删除的参数属性提交参数
    handleClose(index, row) {
      // console.log(row);
      // 减去删除项
      row.attr_vals.splice(index, 1);
      // 调用 请求函数
      this.saveAttrVals(row, '删除');
    },

    // 根据添加的或者删除的参数属性提交参数发起请求
    async saveAttrVals(row, reason) {
      // 发起请求
      const res = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 转换为字符串
        attr_vals: row.attr_vals.join(',')
      });
      if (res.meta.status !== 200) return this.$message.error(`${reason}${this.titleText}属性值失败！`);
      this.$message.success(`${reason}${this.titleText}属性值成功！`);
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    // 根据this.selectedKeys.length来判断添加按钮的禁用状态
    isBtnDisable() {
      return this.selectedKeys.length !== 3;
    },
    // 根据this.selectedKeys.length 计算 分类 id
    cateId() {
      return this.selectedKeys.length === 3 ? this.selectedKeys[2] : null;
    },
    // 根据当前活动页签 来 计算对话框标题和提示的文本
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性';
    }
  }
}
</script>

<style lang="less" scoped>
.alertTip {
  margin: 15px 0;
}

.el-tabs {
  margin-top: 15px;
}

.el-tag {
  margin: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>
